package com.neo.subscribe.stamp.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neo.subscribe.common.util.SpringHelper;
import com.neo.subscribe.stamp.dto.Stamp;
import com.neo.subscribe.stamp.entity.InterfaceConfig;
import com.neo.subscribe.stamp.mapper.StampMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class StampService {

    @Value("${stamp.detail-url-prefix}")
    private String detailUrlPrefix;

    @Autowired
    private StampMapper mapper;

    @Autowired
    private InterfaceConfigService interfaceConfigService;

    @Autowired
    private WxMpService mpService;


    public int saveStampList(List<Stamp> stamps) {
        AtomicInteger count = new AtomicInteger();
        stamps.forEach(i -> {
            int result = mapper.updateBySpuId(i);
            if (result < 1) {
                try {
                    String detailUrl = mpService.shortUrl(String.format(detailUrlPrefix, i.getSpuId()));
                    i.setDetailUrl(detailUrl);
                } catch (WxErrorException e) {
                    log.error("生成短连接失败#{}", ExceptionUtils.getFullStackTrace(e));
                }
                result = mapper.insertNotExist(i);
            }
            if (result < 1) {
                log.info("数据保存失败：{}", JSON.toJSONString(i));
            }
            count.getAndIncrement();
        });
        return count.get();
    }


    public void spiderStampList() {
        List<InterfaceConfig> list = interfaceConfigService.list(10);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        list.forEach(i -> {
            // 判断是否需要预处理
            String pretreatmentClass = i.getRequestPreProcessClass();
            List<InterfaceConfig> alreadyConfigs;
            if (StringUtils.isNoneBlank(pretreatmentClass)) {
                RequestPreProcess pretreatmentProcess = (RequestPreProcess) SpringHelper.getBean(pretreatmentClass);
                alreadyConfigs = pretreatmentProcess.process(i);
            } else {
                alreadyConfigs = Collections.singletonList(i);
            }

            alreadyConfigs.forEach(c -> {
                RequestProcess requestProcess = (RequestProcess) SpringHelper.getBean(c.getRequestProcessClass());
                String responseText = requestProcess.process(c);

                ResponseProcess responseProcess = (ResponseProcess) SpringHelper.getBean(c.getResponseProcessClass());
                responseProcess.process(responseText);
            });
        });
    }


    public String assembleMessage() {
        Date date = new Date();
        StringBuffer sb = new StringBuffer();
        String currentDateTime = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
        String later = DateFormatUtils.format(DateUtils.addHours(date, 24), "yyyy-MM-dd HH:mm:ss");
        // 大余等于当前时间，且小于24小时之后
        sb.append("==== 即将开售 ====\r\n");
        sb.append(assembleMessage(currentDateTime, later));

        String before = DateFormatUtils.format(DateUtils.addHours(date, -24), "yyyy-MM-dd HH:mm:ss");
        // 大余等于24小时之前，且小于当前时间
        sb.append("==== 近期已开售 ====\r\n");
        sb.append(assembleMessage(before, currentDateTime));

        // 大余等于24小时之后
        sb.append("==== 近期开售 ====\r\n");
        sb.append(assembleMessage(later, "9999-12-12"));

        return sb.toString();
    }

    public String assembleMessage(String start, String end) {
        Wrapper<Stamp> wrapper = new QueryWrapper<Stamp>().lambda()
                .ge(Stamp::getSaleStartTime, start)
                .lt(Stamp::getSaleStartTime, end)
                .orderByAsc(Stamp::getSaleStartTime);
        List<Stamp> stamps = mapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(stamps)) {
            return "【暂无】\r\n";
        }
        int index = 1;
        StringBuilder sb = new StringBuilder();
        for (Stamp stamp : stamps) {
            sb.append(index)
                    .append("、名称：").append(stamp.getSpuName())
                    .append("，开售时间：").append(stamp.getSaleStartTime())
                    .append("，起售价格：").append(stamp.getMinPrice()).append(" 元")
                    .append("  <a href=\"").append(stamp.getDetailUrl()).append("\">").append("【详情】</a>")
                    .append(" \r\n");
            index++;
        }
        return sb.toString();
    }


}
